<template>
	<view style="padding: 30rpx;">
		<view class="flex-center topBox">
			<image :src="merchantMsg.logo"></image>
			<view>{{merchantMsg.name}}</view>
		</view>
		<view class="card">
			<view>收款金额</view>
			<view class="flex inputBox">
				<view class="flex">￥</view><input type="digit" :disabled="inputDisabled" v-model="money" />
			</view>
		</view>
		<view v-if="!isPaying" class="submitBtn flex" @click="onSubmitOrder">扫码收款</view>
		<view v-if="isPaying" class="submitBtn flex" @click="toBack">{{payingStatus}}</view>
	</view>
</template>

<script>
	import {
		scanQrCodes,
		setImmediatePayment,
		getOrderPayStatus,
		getQrCodePageMsg,
		haveRaffleTicket,
		getAppConfig,
		checkpaypwdRequest
	} from "@/api/index.js"
	import {
		getConfigJson
	} from "@/api/appapi.js"
	export default {
		data() {
			return {
				webView: '',
				show_pay_keyboard: false,
				payPassword: '',
				isPayCircleDraw: false,
				chouJiangId: 0,
				merchantMsg: {},
				payUrl: "",
				payType: null, //选择的支付方式
				payList: [1, 2, 3, 100, 200], //3-支付宝, 2-微信,1-余额,100-积分(泌豆)
				money: null,
				bid: null, //商家id
				inputDisabled: false,
				isPaying: false,
				payingStatus: '',
				order_status: 0,
				bindbid: null,
				payorderid: '', //支付id
				orderid: 0,
				orderStatusTimer: 0,
				isJumpToPayApp: false
			}
		},
		mounted() {
			// #ifdef H5
			var a = document.getElementsByClassName('uni-page-head-hd')[0]
			a.style.display = 'none';
			// #endif
		},
		async onShow() {
			if (this.orderid && this.payorderid) {
				this.startOrderStatus();
			}
		},
		onHide() {
			clearInterval(this.orderStatusTimer);
			this.orderStatusTimer = 0;
		},
		onUnload() {
			clearInterval(this.orderStatusTimer);
			this.orderStatusTimer = 0;
		},
		onBackPress(options) {
			console.log('from:' + options.from)
			if (options.from === 'navigateBack') {
				return false
			}

			console.log(this.orderStatusTimer)
			clearInterval(this.orderStatusTimer)
			this.orderStatusTimer = 0;
			uni.navigateBack({
				delta: 1
			})

			return true
		},
		async onLoad(opt) {
			const appConfig = await getAppConfig()

			// #ifdef APP-PLUS
			var $this = this;
			plus.globalEvent.addEventListener('plusMessage', msg => {
				if (msg.data.args.data.name == 'postMessage') {
					const info = msg.data.args.data.arg
					if (info.action == "close") {
						try {
							$this.webview.close()
						} catch (e) {}
					}

					if (info.action == "cancel") {
						try {
							$this.webview.close()
						} catch (e) {}

						this.showToast('付款失败')

						this.close('popupPayTips')

						uni.navigateBack({
							delta: 1
						});

					}
				}
			})

			console.log(appConfig)
			let payList = [];
			const sessionData = uni.getStorageSync('sessionData')
			if (sessionData && sessionData.session_id) {
				payList = appConfig.payList;
			} else {
				for (var i = 0; i < appConfig.payList.length; i++) {
					if (appConfig.payList[i] != 1 && appConfig.payList[i] != 100 && appConfig.payList[i] != 200) {
						payList.push(appConfig.payList[i]);
					}
				}
			}
			this.payList = payList
			// #endif


			this.isPayCircleDraw = appConfig.isPayCircleDraw
			this.bid = opt.bid
			this.bindbid = opt.bindbid
			this.chouJiangId = 0;
			this.onGetQrCodePageMsg()

			this.payType = this.payList[0]
		},
		methods: {
			onCloseRegTips() {
				this.close('popupRegTips')
			},
			onReg() {
				uni.reLaunch({
					url: `/pages/login/forgetPassword?yqcode=${this.merchantMsg.yqcode}&type=1&isWebpage=true&t=${new Date().getTime()}`
				});
			},
			gotoCircleDraw() {
				this.close('popupCircleDraw')
				uni.reLaunch({
					url: `/package/mine/circleDraw?id=${this.chouJiangId}&pageType=1`
				});
			},
			async showPayKeyboard() {
				if (this.payType == 1 || this.payType == 100 || this.payType == 200) {
					this.show_pay_keyboard = true
				} else {
					await this.onSetImmediatePayment()
				}
			},
			hidePayKeyboard() {
				this.show_pay_keyboard = false
			},
			async getPayPassword(n) {
				this.payPassword = n.password;
				this.show_pay_keyboard = false

				const res = await checkpaypwdRequest('s=/ApiMy/checkpaypwd', {
					paypwd: this.payPassword
				})
				const {
					id,
					status,
					msg
				} = res.data

				if (status == 1) {
					await this.onSetImmediatePayment()
				} else {
					this.showToast(msg)
				}
			},
			async getHaveRaffleTicket() {
				setTimeout(async () => {
					const res = await haveRaffleTicket('s=/ApiChoujiang/payafter', {
						orderid: this.orderid,
						ordertype: 'offline_order'
					})
					const {
						status,
						id,
						msg
					} = res.data
					console.log(this.orderid)
					console.log(res)
					if (status == 1 && id > 0) {
						this.showToast('付款成功')
						this.onGoPage(1, id)
					} else if (status == 0) {
						this.showToast('付款成功')
						this.onGoPage(0)
					} else {
						this.showToast(msg)
					}
				}, 500);
			},
			getCode() {
				var code = this.getUrlParam('code');
				let BASE_URL = getApp().globalData.BASE_URL
				const local = BASE_URL + '/h5/#/business/pages/business_tab/qrCodePay';
				let redirect_uri = encodeURIComponent(local);
				if (code == null || code === '') {
					window.location.href =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd5bad353b3b7ee81&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
				} else {
					uni.setStorageSync('code', code);
					this.code = code;
				}
			},
			getUrlParam(name) {
				var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
				var r = window.location.search.substr(1).match(reg);
				if (r != null) return unescape(r[2]);
				return null;
			},
			// 提交订单
			async onSubmitOrder() {
				uni.showLoading({
					title: '加载中...'
				})
				if (!this.bid) {
					this.showToast('商家信息错误')
					return
				}

				if (this.money == null || this.money == '') {
					this.showToast('请输入消费金额')
					return
				}

				if (this.orderid && this.payorderid) {
					uni.hideLoading()
					this.onChargeOff()
				} else {
					let url = "";
					url = 's=/ApiZwyRequest/precreateofflineorder'

					const res = await scanQrCodes(url, {
						bid: this.bid,
						money: this.money
					})

					const {
						status,
						orderid,
						payorderid,
						session,
						msg
					} = res.data
					if (status == 1) {
						this.payorderid = payorderid
						this.orderid = orderid
						uni.hideLoading()
						this.onChargeOff()
					} else {
						this.showToast(msg)
					}
				}
			},
			onChargeOff() {
				var that = this

				uni.scanCode({
					onlyFromCamera: true,
					autoZoom: false,
					success: (scanRes) => {
						setTimeout(async () => {
							console.log(scanRes.result)
							uni.showLoading({
								title: '加载中...'
							})
							const res = await scanQrCodes('s=/ApiZwyRequest/connectordermid', {
								bid: that.bid,
								order_mid: scanRes.result,
								orderid: that.orderid,
								payorderid: that.payorderid
							})

							console.log(res)
							const {
								order_info,
								status,
								msg
							} = res.data

							uni.hideLoading()
							if (status == 1) {
								this.isPaying = true;
								this.payingStatus = order_info.status_txt;
								this.inputDisabled = true;

								this.startOrderStatus();
							} else {
								this.showToast(msg)
							}

						}, 800)
					}
				});
			},
			// 判断跳转页面,有抽奖跳抽奖,没抽奖跳tabbar页面
			onGoPage(type, id) {
				setTimeout(() => {
					if (type == 1 && this.isPayCircleDraw) {
						this.chouJiangId = id;
						this.open('popupCircleDraw')
					} else {
						uni.switchTab({
							url: getApp().globalData.HOME_PAGE
						})
					}
				}, 2000)
			},
			// 有抽奖跳转抽奖
			toBack() {
				if (this.order_status != 0) {
					this.onSkip(`/package/mine/businessCenter`);
				}
			},
			startOrderStatus() {
				if (this.orderStatusTimer <= 0) {
					this.orderStatusTimer = setInterval(async () => {
						await this.getOrderStatus();
					}, 3000)

					console.log(this.orderStatusTimer)
				}
			},
			async getOrderStatus() {
				let url = "s=/ApiOrder/docheckorder";

				const res = await getOrderPayStatus(url, {
					bid: this.bid,
					orderid: this.orderid,
					payorderid: this.payorderid
				})
				const {
					id,
					status,
					order_status,
					status_txt,
					msg
				} = res.data
				console.log(res, `ID：${this.payorderid}`)
				this.order_status = order_status;
				if (status == 1 && order_status == 1) {
					clearInterval(this.orderStatusTimer)
					this.payingStatus = status_txt;
					this.showToast('付款成功')
					await this.getYuyin()
				}
			},
			async getYuyin() {
				let url = "s=/ApiPay/mobileyuying";

				const res = await getOrderPayStatus(url, {
					bid: this.bid,
					orderid: this.orderid,
					payorderid: this.payorderid
				})

				console.log(res, "bbbbbbb")

				const {
					status,
					msgtext,
					msg
				} = res.data
				if (status == 1) {
					await this.playYuyin(msgtext)
				}
			},
			async playYuyin(msgtext) {
				var BASE_URL = getApp().globalData.BASE_URL
				var platform = 'app'
				const isAgency = getApp().globalData.isAgency

				// #ifdef H5
				platform = 'h5'
				if (isAgency) {
					BASE_URL = '/api'
				}
				// #endif

				const test2audio = await getConfigJson(
					`${BASE_URL}/ai/text2audio.php?text=${msgtext}`)

				const {
					status,
					url,
					msg
				} = test2audio.data


				console.log(test2audio.data, "cccccccccc")
				if (test2audio.data) {
					let innerAudioContext = uni.createInnerAudioContext();
					innerAudioContext.autoplay = true; //自动播放
					innerAudioContext.loop = false; //循环播放
					innerAudioContext.src = `${BASE_URL}${test2audio.data}`;
					innerAudioContext.onPlay(() => { //可以播放事件
					});
					innerAudioContext.onError((res) => {});
				}
			},
			// 商家信息
			async onGetQrCodePageMsg() {
				var url = "";
				url = `s=/ApiZwyRequest/businessdata&bid=${this.bid}`
				if (this.bindbid) {
					url = `s=/ApiZwyRequest/businessdata&bindbid=${this.bindbid}`
				}

				const res = await getQrCodePageMsg(url)
				const {
					status,
					msg,
					data
				} = res.data
				if (status == 1) {
					this.merchantMsg = data
					if (data.id > 0) {
						this.bid = data.id

					} else {
						this.showToast('商家信息错误')
					}

				} else {
					this.showToast(msg)
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #f7f7f7;
	}

	.hintModalBox {
		padding: 30rpx;
		border-radius: 30rpx;
		width: 600rpx;
		background: #fff;
		height: 700rpx;
		overflow: auto;
		line-height: 50rpx;
		color: #333333;
		font-size: 32rpx;

		.title {
			text-align: center;
			color: #F40E2A;
			font-weight: bold;
			margin-bottom: 30rpx;
		}

		.btn {
			padding: 20rpx 150rpx;
			height: 60rpx;
			background: #F40E2A;
			color: #FFFFFF;
			border-radius: 20rpx;
			margin-top: 50rpx;
		}
	}

	.hintModalPayTipBox {
		padding: 30rpx;
		border-radius: 30rpx;
		width: 600rpx;
		background: #fff;
		height: 300rpx;
		overflow: auto;
		line-height: 50rpx;
		color: #333333;
		font-size: 32rpx;

		.title {
			text-align: center;
			color: #F40E2A;
			font-weight: bold;
			margin-bottom: 30rpx;
		}

		.btnBox {
			display: flex;
			flex-direction: row;

			.btn {
				flex: 1;
				padding: 20rpx;
				height: 60rpx;
				background: #F40E2A;
				color: #FFFFFF;
				border-radius: 20rpx;
				margin-top: 20rpx;
			}
		}

	}

	.hintModalTipBox {
		padding: 60rpx 30rpx 30rpx 30rpx;
		border-radius: 30rpx;
		width: 600rpx;
		background: #fff;
		height: 600rpx;
		overflow: auto;
		line-height: 50rpx;
		color: #333333;
		font-size: 32rpx;

		.title {
			text-align: center;
			color: #333333;
			margin-bottom: 30rpx;
		}

		.btnBox {
			display: flex;
			flex-direction: row;

			.btn {
				flex: 1;
				padding: 20rpx;
				height: 100rpx;
				background: #F40E2A;
				color: #FFFFFF;
				border-radius: 20rpx;
				margin-top: 20rpx;
			}

			.btn_c {
				flex: 1;
				padding: 20rpx;
				height: 100rpx;
				background: #ccc;
				color: #FFFFFF;
				border-radius: 20rpx;
				margin-top: 20rpx;
			}
		}

	}

	.submitBtn {
		margin-top: 10vh;
		color: #fff;
		font-size: 34rpx;
		background: #41644A;
		border-radius: 14rpx;
		padding: 20rpx 0;
		justify-content: center;
	}

	.card {
		border-radius: 30rpx;
		font-size: 32rpx;
		background: #fff;
		padding: 30rpx;
		font-weight: 500;
		margin-top: 98rpx;
		margin-bottom: 75rpx;

		.inputBox {
			height: 130rpx;
			border-bottom: 1px solid #F5F5F5;

			view {
				font-size: 40rpx;
				align-items: center;
			}

			input {
				font-weight: bold;
				padding-left: 40rpx;
				font-size: 46rpx;
				height: 130rpx;
				width: 100%;
			}

		}


	}

	.topBox {
		flex-direction: column;
		font-size: 34rpx;
		font-weight: bold;

		image {
			margin-bottom: 36rpx;
			width: 160rpx;
			height: 160rpx;
			border-radius: 15rpx;
		}
	}
</style>